# coding=utf-8
import logging
import re
import urllib

import sys

import os

import settings

reload(sys)
sys.setdefaultencoding('utf-8')

from venusdemilo import utils, image_downloader
from venusdemilo.customizers import Customizer

image_virtual_server_base_path = "http://localhost/imgs"


class ImageDownloadProcessor(object):
    def processing(self, item):
        html = item["content"]
        host = get_host(item["url"])
        # image_store_base_path = "D:/pics/"

        customizer = get_customizer(item)
        image_virtual_server_relative_path = customizer.get_image_virtual_server_relative_path()
        image_server_virtual_path = '%s/%s' % (image_virtual_server_base_path, image_virtual_server_relative_path)  # virtual server path
        regex = r'<img.*? src=\"(.*?\.(jpg|png|jpeg|bmp))\".*?>'
        pattern = re.compile(regex, re.IGNORECASE);
        # temp = re.findall(pattern, html)
        img_url_iter = re.finditer(pattern, html)
        # img_url_list = ["https://www.ibaodian.com/ueditor/jsp/upload/image/20171206/1512530698945031783.jpg"]
        num = 0
        for img_iter in img_url_iter:
            num += 1
            img_url = img_iter.group(1)
            if is_absolute_url(img_url):
                img_abs_url = img_url
            else:
                img_abs_url = update_to_abs(img_url, host)
            image_name = get_image_file_name(img_abs_url)
            image_downloader.download_image(img_abs_url, image_name, host, customizer)
            new_image_full_path = "%s/%s" % (image_server_virtual_path, image_name)
            item["content"] = item["content"].replace(img_url, new_image_full_path)

        return item


def get_customizer(item):
    host = get_host(item["url"])
    cls_path = utils.match_kv(host, settings.CUSTOMIZER_MAPPING)
    # for (k, v) in settings.CUSTOMIZER_MAPPING.items():
    #     if re.match(k, host):
    #         cls_path = v
    #         break

    if cls_path:
        cls = utils.load_class(cls_path)
        return cls()
    else:
        logging.error("customizer for host: %s not found...would use default one..." % host)
        return Customizer() # return default customizer


def get_host(url):
    protocol, s1 = urllib.splittype(url)
    host, s2 = urllib.splithost(s1)
    host = "%s://%s" % (protocol, host)
    if host.endswith('/'):
        host = host.rstrip('/')
    return host

def is_absolute_url(url):
    is_abs = url.startswith("http://") or url.startswith("https://")
    return is_abs


def update_to_abs(img_relative_url, base_url):
    if img_relative_url.startswith("//"):
        return "http:" + img_relative_url;
    elif img_relative_url.startswith("../"):
        img_relative_url = img_relative_url.replace('../', '')
        img_relative_url = "/" + img_relative_url
    abs_url = base_url + img_relative_url
    return abs_url


def get_image_file_name(img_abs_url):
    filename, ext = os.path.splitext(img_abs_url)
    import re
    strinfo1 = re.compile('^https?://', re.IGNORECASE)
    strinfo2 = re.compile('[/\.\?\=\:]', re.IGNORECASE)

    img_abs_url_tmp = strinfo1.sub('', img_abs_url)
    new_image_file_name = strinfo2.sub('', img_abs_url_tmp)

    full =  new_image_file_name + ext
    if len(full) > 64:
        return full[-64:]
    else:
        return full
